using System;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;

namespace ConvertSourceToHtml.Conversion
{

    /// <summary>
    /// Contains tool methods for working with HTML.
    /// </summary>
    internal static class HtmlTools
    {
        #region Static Methods

        /// <summary>
        /// Encodes the specified <see cref="String"/> value as HTML.
        /// </summary>
        /// <param name="value">The value to encode.</param>
        /// <returns>The encoded value.</returns>
        public static string HtmlEncode(string value)
        {
            StringBuilder encoded;

            Safety.AssertArgumentNotNull("value", value);

            encoded = new StringBuilder();
            foreach (char character in value)
            {
                encoded.Append(HtmlEncode(character));
            }
            return encoded.ToString();
        }

        /// <summary>
        /// Encodes the specified <see cref="Char"/> value as HTML.
        /// </summary>
        /// <param name="value">The value to encode.</param>
        /// <returns>The encoded value.</returns>
        public static string HtmlEncode(char value)
        {
            switch (value)
            {
                case '"':
                    return "&quot;";
                case '&':
                    return "&amp;";
                case '<':
                    return "&lt;";
                case '>':
                    return "&gt;";
                default:
                    if ((value >= ' ') && (value <= '~'))
                    {
                        return value.ToString();
                    }
                    else if (!char.IsControl(value))
                    {
                        return "&#" + ((int)value).ToString(NumberFormatInfo.InvariantInfo) + ";";
                    }
                    else
                    {
                        return "?";
                    }
            }
        }

        #endregion // Static Methods
    }

}
